package com.linln.wxapi;

import java.io.IOException;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.util.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.linln.modules.member.domain.*;
import com.linln.modules.member.service.*;
import com.linln.modules.message.domain.*;
import com.linln.modules.message.repository.MessageMemberLogRepository;
import com.linln.modules.message.repository.MessageRefundRepository;
import com.linln.modules.message.service.*;
import com.linln.wxapi.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jboss.jandex.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.linln.common.enums.TypeEnum;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.JsonUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.store.domain.Storeinfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商户相关小程序接口
 *
 * @author hct
 */
@Api(value = "信息管理")
@RestController
@RequestMapping("/wx/message/{area}")
public class WxApiMessageController {

    @Autowired
    private MessageInfoService messageService;
    @Autowired
    private MessageTypeService typeService;

    @Autowired
    private MessageSetService setService;
    @Autowired
    private MessageTopService topService;

    @Autowired
    private MembernoticeService noticeService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAgentService memberagentService;

    @Autowired
    private MemberShareService membershareService;

    @Autowired
    private MemberCollectService memberCollectService;
    @Autowired
    private AreaCountService areaCountService;

    @Autowired
    private MessageMemberLogService messageMemberLogServiceImpl;

    @Autowired
    private MessageRefundService messageRefundServiceImpl;

    @Autowired
    private MemberOrderService memberOrderService;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取信息分类信息
     *
     * @param appid
     * @param code
     * @return
     */
    @ApiOperation(value = "获取信息分类信息", notes = "获取信息分类信息")
    @RequestMapping(value = "type", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagetype(@PathVariable String area) {

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageType type = new MessageType();
            //type.setPid(0l);
            // 获取数据列表
            Example<MessageType> example = Example.of(type, matcher);
            Sort sort = new Sort(Sort.Direction.ASC, "num");
            List<MessageType> list = typeService.getListByExample(example, sort);

            List<MessageType> parentlist = new ArrayList<MessageType>();
            for (int i = 0; list != null && i < list.size(); i++) {
                MessageType parenttype = list.get(i);
                if (parenttype.getPid() == 0L) {
                    parentlist.add(parenttype);
                }
            }
            for (int j = 0; parentlist != null && j < parentlist.size(); j++) {
                MessageType parenttype = parentlist.get(j);
                List<MessageType> sonTypeList = new ArrayList<MessageType>();
                for (int i = 0; list != null && i < list.size(); i++) {
                    MessageType sontype = list.get(i);
                    if (sontype.getPid() == parenttype.getId()) {
                        sonTypeList.add(sontype);
                    }
                }
                parenttype.setChildList(sonTypeList);

            }
            return ResultVoUtil.success(parentlist);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("异常");
        }
    }

    /**
     * 获取信息分类信息
     *
     * @param appid
     * @param code
     * @return
     */
    @ApiOperation(value = "添加信息分类信息", notes = "添加分类信息")
    @RequestMapping(value = "addtype", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagetypeadd(@PathVariable String area) {

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageType type = new MessageType();
            type.setAddtype(1);
            //type.setPid(0l);
            // 获取数据列表
            Example<MessageType> example = Example.of(type, matcher);
            Sort sort = new Sort(Sort.Direction.ASC, "num");
            List<MessageType> list = typeService.getListByExample(example, sort);

            List<MessageType> parentlist = new ArrayList<MessageType>();
            for (int i = 0; list != null && i < list.size(); i++) {
                MessageType parenttype = list.get(i);
                if (parenttype.getPid() == 0L) {
                    parentlist.add(parenttype);
                }
            }
            for (int j = 0; parentlist != null && j < parentlist.size(); j++) {
                MessageType parenttype = parentlist.get(j);
                List<MessageType> sonTypeList = new ArrayList<MessageType>();
                for (int i = 0; list != null && i < list.size(); i++) {
                    MessageType sontype = list.get(i);
                    if (sontype.getPid() == parenttype.getId()) {
                        sonTypeList.add(sontype);
                    }
                    parenttype.setChildList(sonTypeList);
                }

            }
            return ResultVoUtil.success(parentlist);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("异常");
        }
    }


    /**
     * 获取热门商户信息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @ApiOperation(value = "获取热门信息列表信息", notes = "获取热门信息列表信息")
    @RequestMapping(value = "hotlist", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagehotlist(@PathVariable String area,
                                   @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                   Long type) {
        System.out.println(DateUtils.format(new Date()) + "hotlist area>>" + area + ">>>type==" + type);

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageInfo baseinfo = new MessageInfo();
            baseinfo.setArea(area);
            baseinfo.setMessageStatus(1);
            if (type != null) {
                MessageType messagetype = new MessageType();
                messagetype.setId(type);
                baseinfo.setTypeone(messagetype);
            }
            // 获取数据列表
            Example<MessageInfo> example = Example.of(baseinfo, matcher);
            // Sort sort = new Sort(Sort.Direction.DESC, "istop");
            Sort sort = new Sort(Sort.Direction.DESC, "id");
             /*Sort.Order order1 = new Sort.Order(Sort.Direction.DESC, "istop");
             Sort.Order order2 = new Sort.Order(Sort.Direction.DESC, "id");
             List<Sort.Order> listOrder = new ArrayList<>();
             listOrder.add(order1);
             listOrder.add(order2);
             Sort sort = Sort.by(listOrder);
             
             */
            Page<MessageInfo> list = messageService.getPageList(example, pageNumber, pageSize, sort);
            Map<String, Object> map = new HashMap<String, Object>();

            if (list == null || list.getContent() == null || list.getContent().size() == 0) {
                //没有数据的从其他社区中获取返回
                baseinfo.setArea(null);
                Example<MessageInfo> examplenone = Example.of(baseinfo, matcher);
                list = messageService.getPageList(examplenone, pageNumber, pageSize);
                map.put("list", list.getContent());
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());
                return ResultVoUtil.success(map);
            } else {
                if (pageNumber == 0 || pageNumber == 1) {
                    List<MessageInfo> toplist = messageService.queryListByArea(area, type);
                    List<MessageInfo> memberInfoList = list.getContent();
                    if (toplist != null && toplist.size() > 0) {
                        if (memberInfoList != null && memberInfoList.size() > 0) {
                            List<MessageInfo> listnew = new ArrayList<MessageInfo>();
                            HashSet h1 = new HashSet(memberInfoList);
                            HashSet h2 = new HashSet(toplist);
                            h1.removeAll(h2);
                            listnew.addAll(h1);
                            System.out.println(listnew);
                            //对users按年龄进行排序
                            Collections.sort(listnew, new Comparator<MessageInfo>() {

                                @Override
                                public int compare(MessageInfo o1, MessageInfo o2) {
                                    // 升序
                                    //return o1.getAge()-o2.getAge();
                                    // 降序
                                    // return o2.getAge()-o1.getAge();
                                    // return o2.getAge().compareTo(o1.getAge());
                                    return o2.getId().compareTo(o1.getId());
                                }
                            });
                            map.put("list", listnew);
                        }
                    } else {
                        map.put("list", memberInfoList);
                    }

                } else {
                    map.put("list", list.getContent());
                }
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());


                return ResultVoUtil.success(map);
            }
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");

        }

    }


    /**
     * 获取热门商户信息(置顶部分内容)
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取热门信息列表信息", notes = "获取热门信息列表信息")
    @RequestMapping(value = "toplist", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagetoplist(@PathVariable String area, Long type) {
        System.out.println(DateUtils.format(new Date()) + " messagetoplist>>>>toplist area>>" + area + ">>>type==" + type);

        try {
            // 创建匹配器，进行动态查询匹配
            //满足当前时间置顶的信息
            List<MessageInfo> toplist = messageService.queryListByArea(area, type);
            Map<String, Object> map = new HashMap<String, Object>();
            if (toplist != null && toplist.size() > 0) {
                map.put("toplist", toplist);
            } else {
                toplist=new ArrayList<MessageInfo>();
                map.put("toplist", toplist);

        		/* toplist= messageService.queryTopDayListByArea(area,type);
        		 if(toplist!=null && toplist.size()>0) {
        			 //随机打乱顺序
        		    // Collections.shuffle(toplist);
                     map.put("toplist", toplist);
            	 }*/
            }
            return ResultVoUtil.success(map);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");

        }

    }


    /**
     * 获取热门商户信息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取信息列表信息", notes = "获取信息列表信息")
    @RequestMapping(value = "list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagelist(@PathVariable String area, String title, Long oneType, Long sonType
            ,
                                @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                                @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize
    ) {
        System.out.println(DateUtils.format(new Date()) + "list area>>" + area + ">>>title==" + title + ">>sonType==" + sonType);

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageInfo baseinfo = new MessageInfo();
            baseinfo.setArea(area);
            baseinfo.setMessageStatus(1);
            if (oneType != null && oneType > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(oneType);
                baseinfo.setTypeone(typeone);
            }
            if (sonType != null && sonType > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(sonType);
                baseinfo.setTypetwo(typetwo);
            }
            // 获取数据列表
            Example<MessageInfo> example = Example.of(baseinfo, matcher);
            Sort sort = new Sort(Sort.Direction.DESC, "id");
             /*Sort sort1 = new Sort(Sort.Direction.DESC, "id");
             sort.and(sort1);*/
            Page<MessageInfo> list = messageService.getPageList(example, pageNumber, pageSize, sort);

            if (list.getContent() == null || list.getContent().size() == 0) {
                baseinfo.setArea(null);
                Map<String, Object> map = new HashMap<String, Object>();

                Example<MessageInfo> examplenone = Example.of(baseinfo, matcher);
                Page<MessageInfo> listnone = messageService.getPageList(examplenone, pageNumber, pageSize);
                map.put("list", listnone.getContent());
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());
                return ResultVoUtil.success(map);
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", list.getContent());
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());
                return ResultVoUtil.success(map);
            }
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");

        }

    }

    /**
     * 查询信息信息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "查询信息", notes = "查询信息")
    @RequestMapping(value = "search", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo searchMessage(@PathVariable String area, String keyword, Long oneType, Long sonType,
                                  @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        System.out.println(DateUtils.format(new Date()) + "list area>>" + area + ">>>title==" + keyword + ">>sonType==" + sonType);

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageInfo baseinfo = new MessageInfo();
            baseinfo.setArea(area);
            baseinfo.setMessageStatus(1);
            if (StringUtils.isNoneBlank(keyword)) {
                baseinfo.setTitle(keyword);
            }
            if (oneType != null && oneType > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(oneType);
                baseinfo.setTypeone(typeone);
            }
            if (sonType != null && sonType > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(sonType);
                baseinfo.setTypetwo(typetwo);
            }
            // 获取数据列表
            Example<MessageInfo> example = Example.of(baseinfo, matcher);
            Page<MessageInfo> list = messageService.getPageList(example, pageNumber, pageSize);

            if (list.getContent() == null || list.getContent().size() == 0) {
                return ResultVoUtil.success("暂无数据");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", list.getContent());
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());
                return ResultVoUtil.success(map);
            }
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");

        }

    }


    /**
     * 发布消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "发布消息", notes = "发布消息")
    @RequestMapping(value = "fabu", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messagefabu(@PathVariable String area, MessageInfo messageinfo,
                                Long memberId, Long messageType1, Long messageType2
    ) throws WxErrorException, IOException {
        //,String newArea
        // area=newArea;
        if(!checkMsg(messageinfo.getContent())) {
            return ResultVoUtil.error("发布违规内容");
        }else {
            System.out.println("我正规");
        }
        Gson gson = new Gson();
        String ss = gson.toJson(messageinfo);
        System.out.println(DateUtils.format(new Date()) + "fabu >>" + ss);
        //MemberInfo memberlogin=memberInfoService.getById(memberId);
        MemberAgent agent = memberagentService.getByMemberIdAndArea(memberId, area);
        try {
            if (agent == null || agent.getId() == 0) {

                if (messageinfo.getIstop() == null || messageinfo.getIstop() == 0) {
                    System.out.println("我是普通发布啊");
                    /*//long faCount=messageService.getDayAddCount(memberId);
                     */
                    long facount = messageService.getDayAddCount(memberId);
                    Map<String, Integer> map = new HashMap<String, Integer>();
                    if (facount > 0) {
                        //提示去分享
                        long sharecount = membershareService.getDayAddCount(memberId);
                        if (sharecount > 0) {
                            membershareService.deleteByMemberId(memberId);
                        } else {
                            map.put("limit", 0);
                            return ResultVoUtil.success(map);
                        }
                    }
                    //if(faCount>0) {
                    //可以再发一篇
           			    /*Map<String,Integer> map=new HashMap<String,Integer>();
            			map.put("limit", 0);
               		    return ResultVoUtil.success(map); 
                		long sharecount=membershareService.getDayAddCount(memberId);
           			    Map<String,Integer> map=new HashMap<String,Integer>();
                		if(sharecount>0 && facount>=2) {
                			 map.put("limit", 1);
                			 return ResultVoUtil.success(map); 
                		}else if(sharecount==0 && facount>=1){
                			//可以再发一篇
                			map.put("limit", 0);
                   		    return ResultVoUtil.success(map); 
                		}*/
                    //}
                }

            }
            messageinfo.setMessageStatus(1);
            if (messageinfo.getIstop() == 1) {
                messageinfo.setEndTime(DateUtils.getDateInfo(messageinfo.getStartTime(), messageinfo.getDay()));
                messageinfo.setMessageStatus(0);
                //messageinfo.setCreateDate(DateUtils.getDateHourInfo(messageinfo.getStartTime(), messageinfo.getDeadline()));
            }
            messageinfo.setZannum(0);
            messageinfo.setSharenum(0);
            messageinfo.setReadnum(0);
            messageinfo.setCollectnum(0);
            messageinfo.setPayStatus(0);
            messageinfo.setOrderId(ToolUtil.getRandomString(32));
            if (messageType1 != null && messageType1 > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(messageType1);
                messageinfo.setTypeone(typeone);
            }
            if (messageType2 != null && messageType2 > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(messageType2);
                messageinfo.setTypetwo(typetwo);
            }
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }

            messageinfo = messageService.saveAndSendNotice(messageinfo);
            //
            AreaCount count = areaCountService.findByArea(area);
            if (count == null) {
                count = new AreaCount();
                count.setArea(area);
                count.setMessage_fabunum(1);
                areaCountService.save(count);
            } else {
                areaCountService.updateFabuByArea(area);

            }            //发布审核的消息

            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }

    /**
     * 发布消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     *             adStartTime 开始时间00:00
     * @return
     */
    @ApiOperation(value = "编辑消息", notes = "编辑消息")
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messageedit(@PathVariable String area, MessageInfo messageinfo,
                                Long memberId, String adStartTime
    ) {
        //,String newArea
        // area=newArea;

        Gson gson = new Gson();
        String ss = gson.toJson(messageinfo);
        System.out.println(DateUtils.format(new Date()) + "edit >>" + ss + ">>>>>>>>>>>>>>>>>>>" + adStartTime);
        MemberInfo memberold = memberInfoService.getById(memberId);
        try {
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }
            MessageInfo messageinfoold = messageService.getById(messageinfo.getId());
            if (memberold != null && memberold.getIsagent().intValue() == 1) {
                messageinfoold.setImgs(messageinfo.getImgs());
                messageinfoold.setLogo(messageinfo.getLogo());
                if(messageinfo.getIstop().intValue() > 0){
                    if(StringUtils.isNotEmpty(messageinfo.getOrderCode())) {
                        messageinfoold.setOrderId(messageinfo.getOrderCode());
                    }
                    messageinfoold.setIstop(1);
                    //修改状态是否置顶
                    //messageinfoold.setIstop(messageinfo.getIstop());
                    //期限
                    messageinfoold.setDay(messageinfo.getDay());
                    BigDecimal b1 = new BigDecimal(messageinfoold.getFee());
                    BigDecimal b2 = new BigDecimal(messageinfo.getFee());
                    Double addFee = b1.add(b2).doubleValue();
                    //修改支付总额  续费累加
                    messageinfoold.setFee(addFee);

                    //开始日期+时间  当过期了 用现在的时候计算,没过期直接用结束时间续期
                    Date date=new Date();
                    if(messageinfoold.getEndTime().before(date)) {
                        messageinfoold.setPayStatus(0);
                        messageinfoold.setOrderId(ToolUtil.getRandomString(32));
                        messageinfoold.setMessageStatus(0);
                        messageinfoold.setEndTime(DateUtils.getDateInfo(date, messageinfoold.getDay()));
                    }else {
                        messageinfoold.setEndTime(DateUtils.getDateInfo(messageinfoold.getEndTime(), messageinfoold.getDay()));
                    }

                }
                Date oldStartime = messageinfoold.getStartTime();
                String dateinfo = DateUtils.format(oldStartime, "yyyy-MM-dd");
                String dateinfoss = dateinfo + " " + adStartTime;
                Date newStartTime = DateUtils.strToDate(dateinfoss, "yyyy-MM-dd HH:mm");
                messageinfoold.setStartTime(newStartTime);
            }

            messageinfoold.setTitle(messageinfo.getTitle());
            messageinfoold.setDetails(messageinfo.getDetails());
            messageinfo = messageService.save(messageinfoold);

            //
            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }

    /**
     * 发布顺风车消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "发布顺风车消息", notes = "发布顺风车消息")
    @RequestMapping(value = "che/fabu", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messageshunfengchefabu(@PathVariable String area, Long memberId, Long messageType1, Long messageType2, MessageInfo messageinfo, ShunfengMessageInfo shunfeng) {
        Gson gson = new Gson();
        String ss = gson.toJson(shunfeng);
        System.out.println(DateUtils.format(new Date()) + "shunfengmessageinfo>>" + ss);
        String sssss = gson.toJson(messageinfo);
        System.out.println(DateUtils.format(new Date()) + "fabu >>" + sssss);

        // MemberInfo memberlogin=memberInfoService.getById(memberId);
        //查看我是不是当前area的代理商
        MemberAgent agent = memberagentService.getByMemberIdAndArea(memberId, area);
        try {
            if (agent == null || agent.getId() == 0) {
                if (messageinfo.getIstop() == null || messageinfo.getIstop() == 0) {
                    long facount = messageService.getDayAddCount(memberId);
                    Map<String, Integer> map = new HashMap<String, Integer>();
                    if (facount > 0) {
                        //提示去分享
                        long sharecount = membershareService.getDayAddCount(memberId);
                        if (sharecount > 0) {
                            membershareService.deleteByMemberId(memberId);
                        } else {
                            map.put("limit", 0);
                            return ResultVoUtil.success(map);
                        }
                    }
	    		    	/*long facount=messageService.getDayAddCount(memberId);
	    		    	if(facount>0) {
	    		    		Map<String,Integer> map=new HashMap<String,Integer>();
	             			map.put("limit", 0);
	                		return ResultVoUtil.success(map);
	    		    		long sharecount=membershareService.getDayAddCount(memberId);
	    		    		System.out.println("sharecount===="+sharecount);
	    		    		System.out.println("facount===="+facount);
	    		    		Map<String,Integer> map=new HashMap<String,Integer>();
	                		if(sharecount>0 && facount>=2) {
	                			 map.put("limit", 1);
	                			 return ResultVoUtil.success(map); 
	                		}else if(sharecount==0 && facount>=1){
	                			//可以再发一篇
	                			map.put("limit", 0);
	                   		    return ResultVoUtil.success(map); 
	                		}
	    		    	}*/
                }
            }
            messageinfo.setTitle(shunfeng.getStartAddress() + "-" + shunfeng.getEndAddress());
            //messageinfo.setDetails("出发时间："+DateUtils.format(shunfeng.getChufaTime()));
            messageinfo.setAddress(shunfeng.getPersoncount() + "");
            messageinfo.setMessageStatus(1);

            if (messageinfo.getIstop() == 1) {
                messageinfo.setEndTime(DateUtils.getDateInfo(messageinfo.getStartTime(), messageinfo.getDay()));
                messageinfo.setMessageStatus(0);

            }
            messageinfo.setZannum(0);
            messageinfo.setSharenum(0);
            messageinfo.setReadnum(0);
            messageinfo.setCollectnum(0);
            if (messageType1 != null && messageType1 > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(messageType1);
                messageinfo.setTypeone(typeone);
            }
            if (messageType2 != null && messageType2 > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(messageType2);
                messageinfo.setTypetwo(typetwo);
            }
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }
            messageinfo.setPayStatus(0);
            messageinfo.setOrderId(ToolUtil.getRandomString(32));
            messageinfo.setContent(JsonUtils.toJson(shunfeng));
            messageinfo = messageService.saveAndSendNotice(messageinfo);
            AreaCount count = areaCountService.findByArea(area);
            if (count == null) {
                count = new AreaCount();
                count.setArea(area);
                count.setMessage_fabunum(1);
                areaCountService.save(count);
            } else {
                areaCountService.updateFabuByArea(area);

            }
            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }


    /**
     * 发布顺风车消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "编辑顺风车消息", notes = "发布顺风车消息")
    @RequestMapping(value = "che/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messageshunfengcheedit(@PathVariable String area, Long memberId, String adStartTime, MessageInfo messageinfo, ShunfengMessageInfo shunfeng) {
        //,String newArea
        // area=newArea;

        Gson gson = new Gson();
        String ss = gson.toJson(shunfeng);
        System.out.println("shunfengmessageinfo>>" + ss);
        String sssss = gson.toJson(messageinfo);
        System.out.println("shunfengmessageinfo bianji >>" + sssss);

        try {
            MemberAgent agent = memberagentService.getByMemberIdAndArea(memberId, area);
            if (agent == null || agent.getId() == 0) {    //我不是代理商

            }
            messageinfo.setTitle(shunfeng.getStartAddress() + "-" + shunfeng.getEndAddress());
            messageinfo.setAddress(shunfeng.getPersoncount() + "");


            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }
            messageinfo.setContent(JsonUtils.toJson(shunfeng));
            MemberInfo memberold = memberInfoService.getById(memberId);

            MessageInfo messageinfoold = messageService.getById(messageinfo.getId());
            if (memberold != null && memberold.getIsagent() != null && memberold.getIsagent().intValue() == 1) {
                messageinfoold.setImgs(messageinfo.getImgs());
                messageinfoold.setLogo(messageinfo.getLogo());
                if(messageinfo.getIstop().intValue() > 0){
                    if(StringUtils.isNotEmpty(messageinfo.getOrderCode())){
                        messageinfoold.setOrderId(messageinfo.getOrderCode());
                        //修改状态是否置顶
                        messageinfoold.setIstop(messageinfo.getIstop());
                        //期限
                        messageinfoold.setDay(messageinfo.getDay());
                        BigDecimal b1 = new BigDecimal(messageinfoold.getFee());
                        BigDecimal b2 = new BigDecimal(messageinfo.getFee());
                        Double addFee = b1.add(b2).doubleValue();
                        //修改支付总额  续费累加
                        messageinfoold.setFee(addFee);
                        //开始日期+时间
                        messageinfoold.setEndTime(DateUtils.getDateInfo(messageinfoold.getEndTime(), messageinfoold.getDay()));
                    }
                }
                Date oldStartime = messageinfoold.getStartTime();
                String dateinfo = DateUtils.format(oldStartime, "yyyy-MM-dd");
                String dateinfoss = dateinfo + " " + adStartTime;
                Date newStartTime = DateUtils.strToDate(dateinfoss, "yyyy-MM-dd HH:mm");
                messageinfoold.setStartTime(newStartTime);
                try {
                    System.out.println("messageinfoold.getStartTime()==" + messageinfoold.getStartTime());
                    System.out.println("messageinfoold.getDeadline()==" + messageinfoold.getDeadline());
                    //messageinfoold.setCreateDate(DateUtils.getDateHourInfo(messageinfoold.getStartTime(), messageinfoold.getDeadline()));
                } catch (Exception e) {

                }
                //messageinfoold.setCreateDate(DateUtils.getDateHourInfo(messageinfoold.getStartTime(), messageinfoold.getDeadline()));

            }
            messageinfoold.setContent(messageinfo.getContent());
            messageinfoold.setAddress(messageinfo.getAddress());
            messageinfoold.setTitle(messageinfo.getTitle());
            messageinfoold.setDetails(messageinfo.getDetails());
            messageinfo = messageService.save(messageinfoold);
            //areaCountService.updateFabuByArea(area);
            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }


    /**
     * 获取信息详情
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取消息详情", notes = "获取消息详情信息")
    @RequestMapping(value = "detail", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagedetail(@PathVariable String area, Long id) {

        try {
            if(area==null || area.equals("")){
                area="000000";
            }
            MessageInfo baseinfo = messageService.getById(id);
            if (baseinfo != null) {
                if (baseinfo.getReadnum() == null) {
                    baseinfo.setReadnum(1);
                } else {
                    baseinfo.setReadnum(baseinfo.getReadnum() + 1);
                }
                messageService.updateIsReadAddById(id);
                //统计访问量
                AreaCount count = areaCountService.findByArea(area);
                if (count == null) {
                    count = new AreaCount();
                    count.setArea(area);
                    count.setMessage_readnum(1);
                    areaCountService.save(count);
                } else {
                    areaCountService.updateReadNumByArea(area);
                }
            } else {
                return ResultVoUtil.error("信息不存在");

            }
            return ResultVoUtil.success(baseinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }


    /**
     * 发布消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "发布招聘消息", notes = "发布招聘消息")
    @RequestMapping(value = "/zhaopin/fabu", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messagezhaopinfabu(@PathVariable String area, Long memberId, MessageInfo messageinfo, Long messageType1, Long messageType2, ZhaopinMessageInfo zhaopinmessageinfo) throws WxErrorException, IOException {
        //,String newArea
        // area=newArea;
        if(!checkMsg(messageinfo.getContent())) {
            return ResultVoUtil.error("发布违规内容");
        }else {
            System.out.println("我正规");
        }
        Gson gson = new Gson();
        String ss = gson.toJson(zhaopinmessageinfo);
        System.out.println(DateUtils.format(new Date()) + "zhaopinmessageinfo>>" + ss);
        messageinfo.setMessageStatus(1);
        MemberAgent agent = memberagentService.getByMemberIdAndArea(memberId, area);

        if (agent == null || agent.getId() == 0) {
            if (messageinfo.getIstop() == null || messageinfo.getIstop() == 0) {

                long facount = messageService.getDayAddCount(memberId);
                Map<String, Integer> map = new HashMap<String, Integer>();
                if (facount > 0) {
                    //提示去分享
                    long sharecount = membershareService.getDayAddCount(memberId);
                    if (sharecount > 0) {
                        membershareService.deleteByMemberId(memberId);
                    } else {
                        map.put("limit", 0);
                        return ResultVoUtil.success(map);
                    }
                }
    		
    	/*long facount=messageService.getDayAddCount(memberId);
    	if(facount>0) {
    		Map<String,Integer> map=new HashMap<String,Integer>();
 			map.put("limit", 0);
    		return ResultVoUtil.success(map);
    		long sharecount=membershareService.getDayAddCount(memberId);
    		Map<String,Integer> map=new HashMap<String,Integer>();
    		if(sharecount>0 && facount>=2) {
    			 map.put("limit", 1);
    			 return ResultVoUtil.success(map); 
    		}else if(sharecount==0 && facount>=1){
    			//可以再发一篇
    			map.put("limit", 0);
       		    return ResultVoUtil.success(map); 
    		}

    	}*/
            }
        }

        try {
            messageinfo.setContent(JsonUtils.toJson(zhaopinmessageinfo));
            if (messageinfo.getIstop() == 1) {
                messageinfo.setEndTime(DateUtils.getDateInfo(messageinfo.getStartTime(), messageinfo.getDay()));
                messageinfo.setMessageStatus(0);

            }
            messageinfo.setArea(area);
            if (messageType1 != null && messageType1 > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(messageType1);
                messageinfo.setTypeone(typeone);
            }
            if (messageType2 != null && messageType2 > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(messageType2);
                messageinfo.setTypetwo(typetwo);
            }
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }
            messageinfo.setOrderId(ToolUtil.getRandomString(32));
            messageinfo.setZannum(0);
            messageinfo.setSharenum(0);
            messageinfo.setReadnum(0);
            messageinfo.setCollectnum(0);
            messageinfo.setPayStatus(0);
            messageinfo = messageService.saveAndSendNotice(messageinfo);
            AreaCount count = areaCountService.findByArea(area);
            if (count == null) {
                count = new AreaCount();
                count.setArea(area);
                count.setMessage_fabunum(1);
                areaCountService.save(count);
            } else {
                areaCountService.updateFabuByArea(area);

            }
            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }


    /**
     * 发布消息
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "编辑招聘消息", notes = "发布招聘消息")
    @RequestMapping(value = "/zhaopin/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResultVo messagezhaopinedit(@PathVariable String area, Long memberId, MessageInfo messageinfo, String adStartTime, ZhaopinMessageInfo zhaopinmessageinfo) throws WxErrorException, IOException {
        Gson gson = new Gson();
        String ss = gson.toJson(zhaopinmessageinfo);
        System.out.println(DateUtils.format(new Date()) + "/zhaopin/edit>>" + ss);
        //,String newArea
        // area=newArea;
        if(!checkMsg(messageinfo.getContent())) {
            return ResultVoUtil.error("发布违规内容");
        }else {
            System.out.println("我正规");
        }
        try {
            messageinfo.setContent(JsonUtils.toJson(zhaopinmessageinfo));
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }

            MessageInfo messageinfoold = messageService.getById(messageinfo.getId());
            MemberInfo memberold = memberInfoService.getById(memberId);
            if (memberold != null && memberold.getIsagent() != null && memberold.getIsagent().intValue() == 1) {
                messageinfoold.setImgs(messageinfo.getImgs());
                messageinfoold.setLogo(messageinfo.getLogo());
                if(messageinfo.getIstop().intValue() > 0){
                    if(StringUtils.isNotEmpty(messageinfo.getOrderCode())){
                        messageinfoold.setOrderId(messageinfo.getOrderCode());
                        //修改状态是否置顶
                        messageinfoold.setIstop(messageinfo.getIstop());
                        //期限
                        messageinfoold.setDay(messageinfo.getDay());
                        BigDecimal b1 = new BigDecimal(messageinfoold.getFee());
                        BigDecimal b2 = new BigDecimal(messageinfo.getFee());
                        Double addFee = b1.add(b2).doubleValue();
                        //修改支付总额  续费累加
                        messageinfoold.setFee(addFee);
                        //开始日期+时间
                        messageinfoold.setEndTime(DateUtils.getDateInfo(messageinfoold.getEndTime(), messageinfoold.getDay()));
                    }
                }
                Date oldStartime = messageinfoold.getStartTime();
                String dateinfo = DateUtils.format(oldStartime, "yyyy-MM-dd");
                String dateinfoss = dateinfo + " " + adStartTime;
                Date newStartTime = DateUtils.strToDate(dateinfoss, "yyyy-MM-dd HH:mm");
                messageinfoold.setStartTime(newStartTime);
            }
            messageinfoold.setContent(messageinfo.getContent());
            messageinfoold.setTitle(messageinfo.getTitle());
            messageinfoold.setDetails(messageinfo.getDetails());
            messageinfo = messageService.save(messageinfoold);


            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }


    /**
     * 获取商户设置基础信息
     *
     * @param area 区域
     * @return
     */
    @ApiOperation(value = "获取信息设置信息", notes = "获取信息设置信息")
    @RequestMapping(value = "messageset", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messageset(@PathVariable String area) {

        try {
            MessageSet set = setService.getById(1L);
            return ResultVoUtil.success(set);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("失败");

        }

    }


    /**
     * 获取置顶信息
     *
     * @param area 区域
     * @return
     */
    @ApiOperation(value = "获取信息设置信息", notes = "获取信息设置信息")
    @RequestMapping(value = "messagetop", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagetop(@PathVariable String area) {

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageTop baseinfo = new MessageTop();
            // 获取数据列表
            Example<MessageTop> example = Example.of(baseinfo, matcher);

            List<MessageTop> list = topService.getList(example);
            return ResultVoUtil.success(list);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("失败");

        }

    }

    /**
     * 收藏及取消收藏
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "是否已收藏", notes = "是否已收藏")
    @RequestMapping(value = "iscollect", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo mymessagecollect(@PathVariable String area, Long messageId, Long memberId) {

        try {
            MemberCollect collect = memberCollectService.getByMemberIdAndTypeId(memberId, TypeEnum.MESSAGE.getCode(), messageId);

            if (collect != null && collect.getId() > 0) {
                return ResultVoUtil.success(1);
            }
            return ResultVoUtil.success(0);
        } catch (Exception e) {
            return ResultVoUtil.error("失败");
        }

    }

    /**
     * 收藏及取消收藏
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "收藏信息", notes = "收藏信息")
    @RequestMapping(value = "collect", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo messagecollect(@PathVariable String area, Long messageId, Long memberId) {

        try {

            MemberCollect collect = memberCollectService.getByMemberIdAndTypeId(memberId, TypeEnum.MESSAGE.getCode(), messageId);

            if (collect != null && collect.getId() > 0) {
                memberCollectService.delCollect(collect.getId());
                //TODO对应的消息数量减一
                messageService.updateIsCollectSubById(messageId);
                //取消收藏
            } else {
                collect = new MemberCollect();
                collect.setType(TypeEnum.MESSAGE.getCode());
                collect.setTypeId(messageId);
                collect.setArea(area);
                collect.setMemberId(memberId);
                collect = memberCollectService.save(collect);
                messageService.updateIsCollectAddById(messageId);
                //对应的消息数量加1
                AreaCount count = areaCountService.findByArea(area);
                if (count == null) {
                    count = new AreaCount();
                    count.setArea(area);
                    count.setMessage_collectnum(1);
                    areaCountService.save(count);
                } else {
                    areaCountService.updateCollectByArea(area);
                }
            }
            return ResultVoUtil.success(collect);
        } catch (Exception e) {
            return ResultVoUtil.error("失败");
        }

    }

    /**
     * 获取我的置顶信息(置顶部分内容)
     *
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取置顶信息列表信息", notes = "获取热门信息列表信息")
    @RequestMapping(value = "mytoplist", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo mytoplist(@PathVariable String area, Long memberId, String keyword,
                              @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize

    ) {

        System.out.println(DateUtils.format(new Date()) + "toplist area>>" + area + ">>>memberId==" + memberId);

        try {
            // 创建匹配器，进行动态查询匹配
            //满足当前时间置顶的信息
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("title", match -> match.contains());
            MessageInfo baseinfo = new MessageInfo();
            baseinfo.setMessageStatus(1);
            baseinfo.setPayStatus(1);
            if (keyword != null && "".equals(keyword)) {
                baseinfo.setTitle(keyword);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            Example<MessageInfo> examplenone = null;
            MemberAgent memberAgent = memberagentService.getByMemberIdAndArea(memberId, area);
            Page<MessageInfo> list = null;
            if (memberAgent != null) {
                baseinfo.setArea(area);
                examplenone = Example.of(baseinfo, matcher);

                list = messageService.getPageList(examplenone, pageNumber, pageSize);

            } else {
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.setId(memberId);
                baseinfo.setMember(memberInfo);
                examplenone = Example.of(baseinfo, matcher);
                list = messageService.getPageList(examplenone, pageNumber, pageSize);

            }

            map.put("list", list.getContent());
            map.put("pageNumber", list.getPageable().getPageNumber() + 1);
            map.put("pageSize", list.getPageable().getPageSize());
            map.put("pageCount", list.getTotalPages());
            map.put("allCount", list.getTotalElements());


            return ResultVoUtil.success(map);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");

        }

    }

    @ApiOperation(value = "记录浏览记录", notes = "记录浏览记录")
    @RequestMapping(value = "saveBrowseLog", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String saveBrowseLog(Long messageId, Long memberId) {
        MessageMemberLog messageMemberLog = new MessageMemberLog();
        MemberInfo member = new MemberInfo();
        member.setId(memberId);
        messageMemberLog.setMember(member);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setId(messageId);
        messageMemberLog.setMessageInfo(messageInfo);
        messageMemberLog.setCreateTime(new Date());
        messageMemberLog.setUpdateTime(new Date());
        MessageMemberLog messageMemberLog1 = messageMemberLogServiceImpl.insertMessageMemberLog(messageMemberLog);
        if (messageMemberLog1 != null && messageMemberLog1.getId() != null && messageMemberLog1.getId().longValue() > 0l) {
            return "ok";
        }
        return "error";
    }

    @ApiOperation(value = "获取当前信息查看记录", notes = "获取当前信息查看记录")
    @RequestMapping(value = "getMemberList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public List<MemberInfo> getMemberList(Long messageId) {
        List<MessageMemberLog> messageMemberLogs = messageMemberLogServiceImpl.getMemberListByMessage(messageId);
        Set<Long> memeberIds = new HashSet<>();
        for (MessageMemberLog messageMemberLog : messageMemberLogs
        ) {
            memeberIds.add(messageMemberLog.getMember().getId());
        }
        List<MemberInfo> members = new ArrayList<>();
        for (Long id : memeberIds
        ) {
            MemberInfo memberInfo = memberInfoService.getById(id);
            members.add(memberInfo);
        }
        return members;
    }

    @ApiOperation(value = "判断当前用户是否有信息", notes = "判断当前用户是否有信息")
    @RequestMapping(value = "isHasMessage", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Integer isHasMessage(Long memberId) {
        List<MessageRefund> messageRefunds = messageRefundServiceImpl.selectUnreadRefund(memberId);
        if (messageRefunds == null) {
            return 0;
        }
        return messageRefunds.size();
    }

    @ApiOperation(value = "阅读当前信息", notes = "阅读当前信息")
    @RequestMapping(value = "readMessage", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> readMessage(Long refundId,Long messageId) {
        Map<String,Object> map=new HashMap<>();
        Integer integer = messageRefundServiceImpl.readMessage(refundId);
        map.put("messageId",messageId);
        return map;
    }

    @ApiOperation(value = "查询所有消息", notes = "查询所有消息")
    @RequestMapping(value = "selectAllMessage", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public List<MessageRefund> selectAllMessage(Long memberId,Integer type) {
        List<MessageRefund> messageRefunds = messageRefundServiceImpl.selectAllRefund(memberId,type);
        return messageRefunds;
    }

    @ApiOperation(value = "查询是否有未读", notes = "查询是否有未读")
    @RequestMapping(value = "hasNoRead", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Integer hasNoRead(String memberId){
        if(memberId==null || memberId.equals("")|| memberId.equals("undefined"))return 0;
        Long memberIdInfo=Long.valueOf(memberId);
        return messageRefundServiceImpl.hasNoRead(memberIdInfo);
    }


    @ApiOperation(value = "续费置顶消息", notes = "续费置顶消息")
    @RequestMapping(value = "renewMessage", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResultVo renewMessage(@PathVariable String area, MessageInfo messageinfo,
                                 Long memberId, Long messageType1, Long messageType2) {
        Gson gson = new Gson();
        String ss = gson.toJson(messageinfo);
        System.out.println(DateUtils.format(new Date()) + "fabu >>" + ss);
        //
        MemberAgent agent = memberagentService.getByMemberIdAndArea(memberId, area);
        try {
        	//
            if (agent == null || agent.getId() == 0) {
                if (messageinfo.getIstop() == null || messageinfo.getIstop() == 0) {
                    System.out.println("我是普通发布啊");
                    long facount = messageService.getDayAddCount(memberId);
                    Map<String, Integer> map = new HashMap<String, Integer>();
                    if (facount > 0) {
                        //提示去分享
                        long sharecount = membershareService.getDayAddCount(memberId);
                        if (sharecount > 0) {
                            membershareService.deleteByMemberId(memberId);
                        } else {
                            map.put("limit", 0);
                            return ResultVoUtil.success(map);
                        }
                    }
                }

            }
			messageinfo.setMessageStatus(1);
            if (messageinfo.getIstop() == 1) {
                messageinfo.setEndTime(DateUtils.getDateInfo(messageinfo.getStartTime(), messageinfo.getDay()));
                messageinfo.setMessageStatus(0);
            }

            messageinfo.setPayStatus(0);
            messageinfo.setOrderId(ToolUtil.getRandomString(32));
            if (messageType1 != null && messageType1 > 0) {
                MessageType typeone = new MessageType();
                typeone.setId(messageType1);
                messageinfo.setTypeone(typeone);
            }
            if (messageType2 != null && messageType2 > 0) {
                MessageType typetwo = new MessageType();
                typetwo.setId(messageType2);
                messageinfo.setTypetwo(typetwo);
            }
            if (memberId != null && memberId > 0) {
                MemberInfo member = new MemberInfo();
                member.setId(memberId);
                messageinfo.setMember(member);
            }
			//更新当前  的  置顶消息数据
            messageinfo = messageService.saveAndSendNotice(messageinfo);
            //
            AreaCount count = areaCountService.findByArea(area);
            if (count == null) {
                count = new AreaCount();
                count.setArea(area);
                count.setMessage_fabunum(1);
                areaCountService.save(count);
            } else {
                areaCountService.updateFabuByArea(area);

            }            //发布审核的消息

            return ResultVoUtil.success(messageinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }
    }



	@ApiOperation(value = "根据订单号查询消息", notes = "根据订单号查询消息")
	@RequestMapping(value = "selectByOrder", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public ResultVo selectByOrder(String  orderCode){
        MemberOrder memberOrder = memberOrderService.findByOrderCode(orderCode);
        if(memberOrder != null){
            try {
                MessageInfo baseinfo = messageService.getById(memberOrder.getId());
                if (baseinfo != null) {
                    if (baseinfo.getReadnum() == null) {
                        baseinfo.setReadnum(1);
                    } else {
                        baseinfo.setReadnum(baseinfo.getReadnum() + 1);
                    }
                    messageService.updateIsReadAddById(memberOrder.getId());
                    //统计访问量
                    AreaCount count = areaCountService.findByArea(memberOrder.getArea());
                    if (count == null) {
                        count = new AreaCount();
                        count.setArea(memberOrder.getArea());
                        count.setMessage_readnum(1);
                        areaCountService.save(count);
                    } else {
                        areaCountService.updateReadNumByArea(memberOrder.getArea());
                    }
                } else {
                    return ResultVoUtil.error("信息不存在");

                }
                return ResultVoUtil.success(baseinfo);
            } catch (Exception e) {
                this.logger.error(e.getMessage(), e);
                return ResultVoUtil.error("接口异常");
            }
        }
        return ResultVoUtil.error("信息不存在");
    }

    public Boolean checkMsg(String content) throws WxErrorException, IOException {
        /*WxMaService wxService = WxMaConfiguration.getWxMaService();
        System.out.println("wxService====="+wxService);
        String token=wxService.getAccessToken();
        System.out.print("token====="+token);
        Map<String, String> map = new HashMap<>();
        String url="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" +token;
        map.put("content", content);
        Map<String, String> contentmap = new HashMap<String, String>();
        contentmap.put("content", content);
        String json = JSONObject.toJSONString(contentmap);
        System.out.println("json is = "+json);
        JSONObject msg = doPost(url, json);
        if(((Integer)msg.get("errcode")).intValue()==0 && msg.get("errmsg").toString().equals("ok")){
            //代表正常
            return true;
        }else{
            return false;
        }*/
        return true;
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url,String json){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json,"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            System.out.println(post);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}

    

